import 'package:flutter/material.dart';
import '../../Model/post.dart';

class PostDataSource extends DataTableSource {
  final List<Post> _posts = posts;
  int _selectedCount = 0;

  @override
  int get rowCount => _posts.length;

  @override
  bool get isRowCountApproximate => false;

  @override
  int get selectedRowCount => _selectedCount;

  @override
  DataRow getRow(int index) {
    return DataRow.byIndex(
      index: index,
      cells: <DataCell>[
        DataCell(
          Container(
            width: 100,
            child: Text(_posts[index].title)
          )
        ),
        DataCell(Text(_posts[index].author)),
        DataCell(
          Container(
            width: 50,
            height: 50,
            child: Image.network(
              _posts[index].imageUrl,
              fit: BoxFit.fill,
            )
          )
          
        ),
      ]
    );
  }

  void _sort(getField(post), bool assending) {
    _posts.sort((a, b) {
      if (!assending) {
        final c = a;
        a = b;
        b = c;
      }
      final aValue = getField(a);
      final bValue = getField(b);
      return Comparable.compare(aValue, bValue);
    });

    notifyListeners();
  }
}

class PaginatedDataTableDemo extends StatefulWidget {
  PaginatedDataTableDemo({Key key}) : super(key: key);

  @override
  _PaginatedDataTableDemoState createState() => _PaginatedDataTableDemoState();
}

class _PaginatedDataTableDemoState extends State<PaginatedDataTableDemo> {
  int _sortColumnIndex;
  bool _sortAscending = false;

  final PostDataSource _postDataSource = PostDataSource();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('PaginatedDataTableDemo'),
        elevation: 0.0,
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: ListView(
          children: <Widget>[
            PaginatedDataTable(
              rowsPerPage: 5,
              sortColumnIndex: _sortColumnIndex,
              sortAscending: _sortAscending,
              header: Text('Posts'), 
              dataRowHeight: 60,
              columnSpacing: 20,
              columns: [
                DataColumn(
                  label: Text('Title'),
                  onSort: (int index, bool isAccending) {
                    _postDataSource._sort((post) => post.title.length, isAccending);

                    setState(() {
                      _sortColumnIndex = index;
                      _sortAscending = isAccending;
                    });
                  }
                ),
                DataColumn(
                  label: Text('Author'),
                ),
                DataColumn(
                  label: Text('Image'),
                ),
              ], 
              source: _postDataSource
            )
          ],
        )
      ),
    );
  }
}